# -*- coding: utf-8 -*-

__author__ = 'lcc@lavenliu.cn'

import sys
import argparse
import json
from urllib.request import urlopen

parser = argparse.ArgumentParser()
parser.add_argument('--ip-list-file', '-f',
                    action='store',
                    dest='ip_list_file',
                    help='file contains ip(s) which one ip per line to query')
parser.add_argument('--ip', '-i',
                    action='store',
                    dest='ip',
                    help='single ip to query')
results = parser.parse_args()

if len(sys.argv) < 2:
    print('You must enter at least one ip in cmd-line!')
    print('Usage: {} ip | ip_list_file'.format(sys.argv[0]))
    print('eg: {} --ip aaa.bbb.ccc.ddd | -f iplist'.format(sys.argv[0]))
    sys.exit(1)


def get_country(ip_address):
    url = 'http://freegeoip.net/json/'
    resp_json = urlopen(url+ip_address).read().decode('utf-8')
    resp_dict = json.loads(resp_json)
    
    if resp_dict['region_name'] and resp_dict['city']:
        return "[{}]: {}-{}-{}".format(
            resp_dict['ip'],
            resp_dict['country_name'],
            resp_dict['region_name'],
            resp_dict['city'])
    else:
        return "[{}]: {}".format(resp_dict['ip'], resp_dict['country_name'])


if results.ip_list_file:
    try:
        with open(results.ip_list_file) as f:
            ip_addresses = f.readlines()
        for ip_address in ip_addresses:
            print(get_country(ip_address.strip()))
    except FileNotFoundError:
        print('No such file: {}'.format(results.ip_list_file))
    except PermissionError:
        print('Permission denied: {}'.format(results.ip_list_file))
else:
    print(get_country(results.ip))
